<?php

namespace Frieza\Modules\Lottery\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Lottery\LotteryTokenBucket;
use Doraemon\model\Lottery\LotteryActivitySeries;
use Doraemon\model\Lottery\LotteryPrize;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class PrizeController extends Controller
{

    const PAGE_SIZE = 20;


    public function index(Request $request, Content $content, $series_id)
    {
        $where = [
            "AND" => [
                "activity_num_id" => $series_id,
                "p_status" => LotteryPrize::STATUS_NORMAL,
            ],
            'ORDER' => [
                'id' => 'DESC'
            ]
        ];

        $result = [];
        $result['list'] = LotteryPrize::selectByWhere($where);

        unset($where['ORDER']);
        unset($where['LIMIT']);
        $result['total'] = LotteryPrize::selectCount($where);
        $grid = new pGridDataModel($result['list'], $result['total']);
        $gridList = Admin::grid($grid,
            function (Grid $grid) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->column('id');
                $grid->column('activity_num_id', '抽奖活动期数id');
                $grid->column('prize_name', '奖品名');
                $grid->column('pic_id', '奖品图片')->image($this->pic_id, 100, 100);
                $grid->column('price', '参考价格');
                $grid->column('remark', '奖品描述');
                $grid->column('award_num', '奖品数量');
                $grid->column('per', '中奖几率');
                $grid->column('open_type', '开奖方式');
                $grid->column('open_time', '开奖时间');
                $grid->column('open_rule', '中奖规则');
                $grid->column('addtime', '添加时间');
                $grid->column('edittime', '修改时间');
            });

        $content->row($gridList);
        return $content
            ->header('奖品列表')
            ->description(' ')
            ->breadcrumb(['text' => 'lottery']);
    }

    //新建/编辑页面
    public function edit(Content $content, $series_id = 0, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑奖品';
        } else {
            $title = '创建奖品';
        }
        $tab->add("$title", $this->editAction($series_id, $id));
        return $content
            ->header('奖品管理')
            ->breadcrumb(
                [
                    'text' => '奖品列表',
                    'url' => '/series/{series_id}/prize/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function editAction($series_id = 0, $id = 0)
    {
        $common_data = ['activity_num_id' => $series_id];
        if ($id > 0) {
            $data = LotteryPrize::getById($id);
            $form = new Form(array_merge($data, $common_data));
            $form->hidden('id');
        } else {
            $form = new Form($common_data);
        }
        $form->hidden('activity_num_id');

        $form->text('prize_name', '奖品名')->required('奖品名必填');
        $form->text('price', '参考价格')->required('参考价格必填');
        $form->textarea('remark', '奖品描述')->required('奖品描述必填');
        $form->imgUpload('pic_id', '奖品图片', true,
            ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->number('award_num', '奖品数量')->required('奖品数量必填');
        $form->number('per', '中奖几率')->required('中奖几率必填');
        $form->datetime('open_time', '开奖时间')->required();
        $form->text('link', '跳转链接');
        $form->text('push_link', '中奖跳转链接');
        $form->text('open_rule', '中奖规则');

        $form->action('/admin/lottery/series/prize/index/save');

        return $form;
    }

    public function saveSubmit(Request $request)
    {
        $params = $request->all();
        $data = [
            'activity_num_id' => $params['activity_num_id'],
            'prize_name' => $params['prize_name'],
            'pic_id' => $params['pic_id'],
            'price' => $params['price'],
            'remark' => $params['remark'],
            'link' => $params['link'],
            'push_link' => $params['push_link'],
            'award_num' => $params['award_num'],
            'per' => $params['per'],
            'open_time' => $params['open_time'],
            'open_rule' => $params['open_rule']
        ];

        $series_info = LotteryActivitySeries::getById($params['activity_num_id']);


        if (isset($params['id']) && $params['id']) {
            //编辑
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = LotteryPrize::updateData($data, ["id" => $params['id']]);

            // 立即开奖
            // 如果是立即开奖的类型，那么创建令牌桶，给入令牌
            if ($series_info['open_type'] == 1){
                LotteryTokenBucket::initTokenBucket($params['activity_num_id'], $params['id'], $params['award_num']);
            }
        } else {
            //创建
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $data['p_status'] = LotteryPrize::STATUS_NORMAL;
            $rs = LotteryPrize::insertData($data);

            // 立即开奖
            // 如果是立即开奖的类型，那么创建令牌桶，给入令牌
            if ($series_info['open_type'] == 1){
                LotteryTokenBucket::initTokenBucket($params['activity_num_id'], $rs, $params['award_num']);
            }
        }
        if ($rs) {
            $success = new MessageBag([
                'title' => '保存成功,可以去设置投票项啦'
            ]);
            return redirect('/admin/lottery/series/' . $params['activity_num_id'] . '/prize/index')->with(compact('success'));

        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function del(Request $request, $series_id = 0, $id = 0)
    {
        try {
            if ($id) {
                LotteryPrize::updateData(['p_status' => LotteryPrize::STATUS_DELETE], ['id' => $id]);
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);

            } else {
                throw new \Exception('不存在的id');
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json($success);
    }


}
